package com.demo.function;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

/**
 * @author: cyj
 **/
@Slf4j
public class ImageUtils {

    public static void addWaterMark(String srcImgPath, String tarImgPath) throws Exception {
        // 读取原图片信息
        File srcImgFile = new File(srcImgPath);
        //文件转化为图片
        Image srcImage = ImageIO.read(srcImgFile);
        //获取图片的宽
        int srcImgWidth = srcImage.getWidth(null);
        //获取图片的高
        int srcImgHeight = srcImage.getHeight(null);

        // 加水印
        BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufImg.createGraphics();
        g.drawImage(srcImage, 0, 0, srcImgWidth, srcImgHeight, null);
        //根据图片的背景设置水印颜色
        g.setColor(Color.BLACK);
//        g.setFont(font);              //设置字体

        //设置水印的坐标
        g.drawString("画出水印", 50, 50);
        g.drawString("画出水印2", 150, 150);
        g.dispose();

        // 输出图片
        try (FileOutputStream outImgStream = new FileOutputStream(tarImgPath);) {
            ImageIO.write(bufImg, "jpg", outImgStream);
            log.info("添加水印完成");
            outImgStream.flush();
        }

    }
}
